package com.blb.edupayservice.listener;

import com.blb.common.entity.UserCourseOrder;
import com.blb.edupayservice.config.RabbitMQConfig;
import com.blb.edupayservice.feign.CourseServiceFeignClient;
import com.blb.edupayservice.feign.OrderServiceFeignClient;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 处理订单监听器
 */
@Slf4j
@Component
public class OrderHandleListener {

    @Autowired
    private OrderServiceFeignClient orderServiceFeignClient;

    @Autowired
    private CourseServiceFeignClient courseServiceFeignClient;

    /**
     * 处理订单
     */
    @RabbitListener(queues = RabbitMQConfig.ORDER_DEAD_LETTER_QUEUE_NAME)
    public void receiveDeadLetterOrder(Message message, Channel channel)  {
        try{
            String messageId = message.getMessageProperties().getMessageId();
            //获得订单号
            String tradeNo = new String(message.getBody());
            log.info("接收死信! id:{},order:{}",messageId,tradeNo);
            //查询数据库订单状态
            ResponseEntity<UserCourseOrder> entity = orderServiceFeignClient.getOrderByTradeNo(tradeNo);
            UserCourseOrder order = entity.getBody();
            if(order.getStatus() == 0) {
                //如果没有支付就取消订单
                order.setStatus(2);
                orderServiceFeignClient.changeOrderStatus(order);
                //课程活动库存加1
                courseServiceFeignClient.addStock(order.getActivityId());
                log.info("完成订单更新{}",order);
            }
            //手动确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception ex){
            log.error("处理订单出现异常",ex);
        }

    }
}
